<template>
    <div class="w100h100 p-2" :class="$style.bg">
        <div class="all-center">
            <div :class="$style.titleContainer">
                <div ref="titleElement" class="text-ellipsis" :class="$style.title" @mouseenter="animate()">
                    {{ deptName }}
                </div>
            </div>
        </div>
        <div style="width: 100%;height: calc(100% - 2.4vw);padding: 20px 20px 0;" class="justify-between">
            <!-- <div style="width: 50%;height: 100%;" class="relative">
                <partTitle title="盾构机数据" />
                <el-select v-model="shieldMachine" style="width: 180px;right: 0;top: 10px;position: absolute;"
                    @change="getShieldGuidanceParametersList()">
                    <el-option v-for="ele of shieldMachineList" :key="ele.id" :label="ele.deviceName" :value="ele.id" />
                </el-select>
                <div style="width: 100%;height: calc((100% - 2.09vw) / 2)" class="justify-around">
                    <div style="width: 29%;height: 100%;padding-left: 10px;font-size: 20px;font-weight: bold;color: #FFF;">
                        <div class="mt20px">掘进（环）</div>
                        <div>{{ shieldMachineData?.ringNumber ?? 0 }}</div>
                        <div class="mt20px">滚动角（°）</div>
                        <div>{{ shieldMachineData?.rollAngle ?? 0 }}</div>
                        <div class="mt20px">俯仰角（°）</div>
                        <div>{{ shieldMachineData?.pitchAngle ?? 0 }}</div>
                        <div class="mt20px">测量时间</div>
                        <div>{{ shieldMachineData?.measurementTime ?? '--' }}</div>
                    </div>
                    <div id="lineChart1" style="width: 69%;height: 100%;"></div>
                </div>
                <div style="width: 100%;height: calc((100% - 2.09vw) / 2)" class="justify-around">
                    <div id="lineChart2" style="width: 49%;height: 100%;"></div>
                    <div id="lineChart3" style="width: 49%;height: 100%;"></div>
                </div>
            </div> -->
            <div ref="videoContainer" style="width: 100%;height: 100%;" class="relative">
                <partTitle title="监控视频" />
                <el-select v-model="NVR" style="width: 180px;right: 0;top: 10px;position: absolute;" value-key="id"
                    @change="selectNVR()">
                    <el-option v-for="ele of NVRList" :key="ele.id" :label="ele.cameraName" :value="ele" />
                </el-select>
                <div class="flex pointer absolute" :class="$style.typeList">
                    <div class="all-center" :class="[$style.typeListBody, listType === 1 ? $style.clcikType : '']"
                        @click="entListType(1)">
                        2x2
                    </div>
                    <div class="all-center" :class="[$style.typeListBody, listType === 2 ? $style.clcikType : '']"
                        @click="entListType(2)">
                        3x3
                    </div>
                </div>
                <div style="width: 100%;height: calc(100% - 2.09vw);">
                    <div class="wrap" :class="[searchParams.pageSize === 4 ? $style.container2x2 : $style.container3x3]">
                        <div v-for="(ele, index) of cameraList" :key="index">
                            <iframe style="width: 100%;height:100%;border: 0;" :src='ele.showUrl'></iframe>
                        </div>
                    </div>
                    <pagination v-model:total="total" v-model:page="searchParams.pageNum"
                        v-model:limit="searchParams.pageSize" layout="prev, pager, next" @pagination="getCameraList()" />
                </div>
            </div>
        </div>
    </div>
</template>

<script name="Index" lang="ts" setup>
import partTitle from './components/partTitle.vue';
import { onMounted, reactive, ref, onBeforeUnmount } from 'vue';
import * as myHttp1 from '@/api/surveillanceVideo';
import * as myHttp2 from '@/api/shieldMachine';
import * as echarts from 'echarts';
import { useUserStore } from '@/store/modules/user';

let accessToken = '';
let deviceSerial = '';
let timeoutId1: NodeJS.Timeout;
let timeoutId2: NodeJS.Timeout;
let resizeObserver: ResizeObserver;
let lineChart1;
let lineChart2;
let lineChart3;

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { deptName, } = useUserStore();

const title = ref('中煤项目中煤项目中煤项目');
const titleElement = ref<HTMLElement>();

const NVRList = ref([]);
const NVR = ref();
const searchParams = reactive({ pageNum: 1, pageSize: 4, });
const total = ref(0);
const cameraList = ref([]);
const videoContainer = ref<HTMLElement>();
const listType = ref(1);

const shieldMachine = ref();
const shieldMachineData = ref();
const shieldMachineList = ref([]);

const fullScreen = ref(false);

const getNVRList = async () => {
    const res = await myHttp1.getNVRList({ pageNum: 1, pageSize: 999, });
    if (res.code == 200) {
        NVRList.value = res.rows;
        if (NVRList.value.length) {
            NVR.value = NVRList.value[0];
            selectNVR();
        }
    }
};

const selectNVR = async () => {
    deviceSerial = NVR.value.deviceSerial;
    await getEZAccessToken(NVR.value);
    getCameraList();
};

const getEZAccessToken = async ({ appKey, appSecret, }) => {
    const res = await myHttp1.getEZAccessToken({ appKey, appSecret, });
    if (res.code == 200) {
        accessToken = res.msg;
    }
};

const getCameraList = async () => {
    const res = await myHttp1.getCameraList({ accessToken, deviceSerial, ...searchParams, });
    if (res.code == 200) {
        total.value = res.total;
        cameraList.value = res.rows;
        cameraList.value.forEach(ele => {
            ele.showUrl = `${import.meta.env.VITE_APP_CONTEXT_PATH}surveillance-video/view/index.html?accessToken=${accessToken}&deviceSerial=${deviceSerial}&channelNo=${ele.channelNo}&noFullScreen=1`;
        });
    }
};

const animate = () => {
    if (timeoutId1) {
        return;
    }
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    ctx.font = '800 2.4vw/2.4vw Helvetica Neue';
    const width = ctx.measureText(title.value).width;
    if (width / window.innerWidth > 0.257357) {
        titleElement.value.style.marginLeft = `calc(-${width}px)`;
        titleElement.value.style.transition = 'all 10s';
        timeoutId1 = setTimeout(() => {
            titleElement.value.style.marginLeft = '0px';
            titleElement.value.style.transition = 'all 0s';
            clearTimeout(timeoutId1);
            timeoutId1 = undefined;
        }, 10000);
    }
};

const entListType = (type: number) => {
    listType.value = type;
    searchParams.pageSize = type === 1 ? 4 : 9;
    getCameraList();
};

const getShieldMachineList = async () => {
    const res = await myHttp2.getShieldMachineList({ pageNum: 1, pageSize: 999, });
    if (res.code == 200) {
        shieldMachineList.value = res.rows;
        if (shieldMachineList.value.length) {
            shieldMachine.value = shieldMachineList.value[0].id;
            getShieldGuidanceParametersList();
        } else {
            initLineChart1({});
            initLineChart2({});
            initLineChart3({});
        }
    }
};

const getShieldGuidanceParametersList = async () => {
    const res = await myHttp2.getShieldGuidanceParametersList({ shieldId: shieldMachine.value, });
    if (res.code == 200) {
        shieldMachineData.value = res.rows[0];
        initLineChart1(res.rows[0]);
        initLineChart2(res.rows[0]);
        initLineChart3(res.rows[0]);
    }
};

const initLineChart1 = (data: any) => {
    lineChart1?.dispose();
    lineChart1 = echarts.init(document.getElementById('lineChart1'));
    lineChart1.setOption({
        color: ['#0581C3'],
        grid: { top: '15%', bottom: '5%', left: '10%', right: '5%', },
        title: {
            text: `累计里程${data?.accumulatedMileage ?? 0}m`,
            textStyle: { color: '#FFF', },
            right: 0,
            top: 25,
        },
        tooltip: {
            trigger: 'axis',
            backgroundColor: '#082247',
            textStyle: { color: '#FFF', },
            valueFormatter: value => `${value}mm`,
        },
        xAxis: {
            data: ['前', '中', '后'],
            axisLine: {
                symbol: ['none', 'arrow'],
                symbolSize: [6, 6],
                symbolOffset: 5,
                lineStyle: { color: '#FFF', },
            },
            axisTick: { show: false, },
        },
        yAxis: {
            name: '里程/m',
            nameTextStyle: { color: '#FFF', },
            axisLine: {
                show: true,
                symbol: ['none', 'arrow'],
                symbolSize: [6, 6],
                symbolOffset: 5,
                lineStyle: { color: '#FFF', },
            },
            splitLine: { lineStyle: { color: 'transparent', }, },
        },
        series: [
            {
                type: 'line',
                symbol: 'circle',
                symbolSize: 10,
                emphasis: {
                    focus: 'series',
                    label: { show: true, position: 'top', color: 'orange', },
                    itemStyle: { color: 'orange', shadowBlur: 5, shadowColor: 'orange' },
                },
                data: [data?.headMileage ?? 0, data?.middleMileage ?? 0, data?.tailMileage ?? 0],
            },
        ],
    });
};

const initLineChart2 = (data: any) => {
    lineChart2?.dispose();
    lineChart2 = echarts.init(document.getElementById('lineChart2'));
    lineChart2.setOption({
        color: ['#0581C3'],
        grid: { top: '15%', bottom: '5%', left: '10%', right: '5%', },
        title: {
            text: `趋向${data?.horizontalTrend ?? 0}mm/m`,
            textStyle: { color: '#FFF', },
            right: 0,
            top: 25,
        },
        tooltip: {
            trigger: 'axis',
            backgroundColor: '#082247',
            textStyle: { color: '#FFF', },
            valueFormatter: value => `${value}mm`,
        },
        xAxis: {
            data: ['前', '中', '后'],
            axisLine: {
                symbol: ['none', 'arrow'],
                symbolSize: [6, 6],
                symbolOffset: 5,
                lineStyle: { color: '#FFF', },
            },
            axisTick: { show: false, },
        },
        yAxis: {
            name: '水平偏差/mm',
            nameTextStyle: { color: '#FFF', },
            axisLine: {
                show: true,
                symbol: ['none', 'arrow'],
                symbolSize: [6, 6],
                symbolOffset: 5,
                lineStyle: { color: '#FFF', },
            },
            splitLine: { lineStyle: { color: 'transparent', }, },
        },
        series: [
            {
                type: 'line',
                symbol: 'circle',
                symbolSize: 10,
                emphasis: {
                    focus: 'series',
                    label: { show: true, position: 'top', color: 'orange', },
                    itemStyle: { color: 'orange', shadowBlur: 5, shadowColor: 'orange' },
                },
                data: [data?.headHorizontalOffset ?? 0, data?.middleHorizontalOffset ?? 0, data?.tailHorizontalOffset ?? 0],
            },
        ],
    });
};

const initLineChart3 = (data: any) => {
    lineChart3?.dispose();
    lineChart3 = echarts.init(document.getElementById('lineChart3'));
    lineChart3.setOption({
        color: ['#0581C3'],
        grid: { top: '15%', bottom: '5%', left: '10%', right: '5%', },
        title: {
            text: `趋向${data?.verticalTrend ?? 0}mm/m`,
            textStyle: { color: '#FFF', },
            right: 0,
            top: 25,
        },
        tooltip: {
            trigger: 'axis',
            backgroundColor: '#082247',
            textStyle: { color: '#FFF' },
            valueFormatter: value => `${value}mm`,
        },
        xAxis: {
            data: ['前', '中', '后'],
            axisLine: {
                symbol: ['none', 'arrow'],
                symbolSize: [6, 6],
                symbolOffset: 5,
                lineStyle: { color: '#FFF', },
            },
            axisTick: { show: false, },
        },
        yAxis: {
            name: '垂直偏差/mm',
            nameTextStyle: { color: '#FFF', },
            axisLine: {
                show: true,
                symbol: ['none', 'arrow'],
                symbolSize: [6, 6],
                symbolOffset: 5,
                lineStyle: { color: '#FFF', },
            },
            splitLine: { lineStyle: { color: 'transparent', }, },
        },
        series: [
            {
                type: 'line',
                symbol: 'circle',
                symbolSize: 10,
                emphasis: {
                    focus: 'series',
                    label: { show: true, position: 'top', color: 'orange', },
                    itemStyle: { color: 'orange', shadowBlur: 5, shadowColor: 'orange' },
                },
                data: [data?.headVerticalOffset ?? 0, data?.middleVerticalOffset ?? 0, data?.tailVerticalOffset ?? 0],
            },
        ],
    });
};

onMounted(() => {
    getNVRList();
    getShieldMachineList();
    resizeObserver = new ResizeObserver((e) => {
        console.log(e)
        if (timeoutId2) {
            clearTimeout(timeoutId2);
        }
        timeoutId2 = setTimeout(() => {
            lineChart1?.resize();
            lineChart2?.resize();
            lineChart3?.resize();
            const frames = window.frames;
            for (let i = 0; i < frames.length; i++) {
                frames[i].location.reload();
            }
            clearTimeout(timeoutId2);
            timeoutId2 = undefined;
        }, 300);
    });
    resizeObserver.observe(videoContainer.value);
});

onBeforeUnmount(() => {
    proxy?.clearTimers();
    resizeObserver.disconnect();
    lineChart1?.dispose();
    lineChart1 = undefined;
    lineChart2?.dispose();
    lineChart2 = undefined;
    lineChart3?.dispose();
    lineChart3 = undefined;
});
</script>

<style lang="less" module>
.bg {
    background: linear-gradient(to right, #072847, #29527D 50%, #072847);
}

.titleContainer {
    width: 25.7357vw;
    overflow: hidden;
}

.title {
    color: #FFF;
    font-size: 2.4vw;
    line-height: 2.4vw;
    font-weight: 800;
    text-align: center;
    font-family: Helvetica Neue;
}

.typeList {
    width: 6.0417vw;
    height: 1.46vw;
    top: 0.63vw;
    right: 200px;
    border: 1px solid #01FFFF;
    border-radius: .2083vw;

    >div {
        width: 50%;
        height: 100%;
        color: #01FFFF;

        &:hover {
            background: linear-gradient(90deg, #01FFFF 0%, rgba(78, 155, 155, 0.00) 100%);
        }
    }
}

.typeListBody {
    width: 50%;
    height: 100%;
}

.clcikType {
    background: linear-gradient(90deg, #01FFFF 0%, rgba(78, 155, 155, 0.00) 100%);

    p {
        color: #fff
    }
}

.container2x2 {
    height: calc(100% - 72px);
    justify-content: space-between;
    align-content: start;

    >div {
        width: 49.5%;
        height: calc(49.5% - 0.52vw);
        margin: 0.52vw 0 0;
    }
}

.container3x3 {
    height: calc(100% - 72px);
    align-content: start;

    >div {
        width: 32.8%;
        height: calc(33% - 0.52vw);
        margin: 0.52vw 0 0;
    }

    >div:nth-child(3n+2) {
        margin: 0.52vw calc((100% - 32.8% * 3) / 2) 0;
    }
}
</style>
